// pages/home/home.js
import api from '../../utils/api.js';
import network from '../../utils/network.js';
import formatDate from '../../utils/format_date';

const app = getApp();
let pageIndex = 1;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        style: app.globalData.style,
        list: [],
        isRefresh: false,
        visible: false,
        timer: {},
        signTime: ''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.latitude = 30.49984;
        this.longitude = 114.34253;
        this.hasData = true;
        this.name = "";
        wx.getLocation({
            type: 'gcj02',
            success: res => {
                this.latitude = res.latitude;
                this.longitude = res.longitude;
                console.log('当前经纬度：', this.longitude, this.latitude)
                app.getUserInfo().then(user => {
                    this.user = user;
                    return network.postJsonUnLoadding(api.getUserInfoByUserId, {
                        userId: user.id
                    }, 'application/x-www-form-urlencoded')
                }).then(data => {
                    let timer = data.data;
                    if (timer) {
                        let now = timer.endTime;
                        if (timer.startTime + 60 * 60 * 1000 > now && timer.endTime < now) {
                            timer.format = formatDate.formatWeek(timer.startTime, timer.endTime);
                            if (app.getDistance(this.latitude, this.longitude, timer.lat, timer.lng) < app.globalData.distance) {
                                let signTime = formatDate.formatTime(new Date(), 'yyyy.MM.dd HH:mm');
                                network.postJsonUnLoadding(api.activePartUpdate, {
                                    id: timer.id,
                                    activeId: timer.activeId,
                                    userId: this.user.id,
                                    timerId: timer.timerId,
                                    status: 1
                                }).then(res => {
                                    this.setData({
                                        timer,
                                        signTime,
                                        visible: true
                                    })
                                })
                            }
                        }
                    }
                })
            }
        })

        wx.startPullDownRefresh();
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        if (typeof this.getTabBar === 'function' &&
            this.getTabBar()) {
            this.getTabBar().setData({
                selected: 0
            })
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        // const query = wx.createSelectorQuery().in(this);
        // query.select("#head").boundingClientRect((data) => {
        // let windowInfo = wx.getWindowInfo();
        // this.setData({
        //     height: windowInfo.safeArea.bottom - windowInfo.statusBarHeight - 44 - 48,
        //     statusBarHeight: windowInfo.statusBarHeight
        // })
        // }).exec();
    },

    onPullDownRefresh() {
        this.setData({
            isRefresh: true
        })
        pageIndex = 1;
        this.request();
    },
    onReachBottom() {
        if (this.hasData) {
            this.request();
        }
    },

    /**
     * 请求数据 
     * 将每一页的数据放一个数组，即形成一个二维数组,减少页面渲染的次数
     */
    request: function () {
        let param = {
            pageNo: pageIndex,
            pageSize: 20,
            name: this.name,
            lat: this.latitude,
            lng: this.longitude,
            mode: 1
        }

        network.getJson(api.sitePage, param).then(res => {
            this.setData({
                isRefresh: false
            })
            if (pageIndex == 1) {
                this.setData({
                    list: []
                })
            }
            let list = res.data.list;
            for (let i = 0; i < list.length; i++) {
                list[i].images = list[i].images.split(',');
            }
            this.setData({
                list: this.data.list.concat(list)
            })
            if (this.data.list.length < res.data.total) {
                this.hasData = true;
                pageIndex += 1;
            } else {
                this.hasData = false;
            }
        })
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    chooseCity() {
        wx.navigateTo({
            url: '/home/city/city',
        })
    },

    goSiteDetails(e) {
        wx.navigateTo({
            url: '/home/site/site-details?id=' + e.currentTarget.dataset.id
        })
    },

    callPhone(e) {
        wx.makePhoneCall({
            phoneNumber: e.currentTarget.dataset.phone
        })
    },

    navTap(e) {
        const {
            name,
            lng,
            lat
        } = e.currentTarget.dataset;
        wx.openLocation({
            name,
            latitude: lat,
            longitude: lng
        })
    },

    onSearch(e) {
        console.log(e)
        this.name = e.detail.value
        pageIndex = 1;
        this.request();
    },

    onClear() {
        this.name = '';
        pageIndex = 1;
        this.request();
    },

    onVisibleChange(e) {
        this.setData({
            visible: e.detail.visible,
        });
    }
})